package sample.view;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import sample.enums.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginController {

    private static final String version = "0.1";
    @FXML
    public TextField username;
    @FXML
    private PasswordField password;
    @FXML
    private Label tips;
    public static Boolean paid = false;
    public static String uid = null;


    private void showMainScene(Map<String, Object> map) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("main.fxml"));
        Parent root = fxmlLoader.load();
        Login.mainStage.setTitle("Main");
        Scene scene = new Scene(root);
        //scene.getStylesheets().add(Login.class.getResource("login.css").toExternalForm());
        Login.mainStage.setScene(scene);

        MainController controller = fxmlLoader.getController();
        controller.initMap(map);
        if(map.get("paid") != null) {
            this.paid = (Boolean) map.get("paid");
        }
    }

    @FXML
    public void handleRegister() throws IOException {

        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("register.fxml"));
        Parent root = fxmlLoader.load();

        //Login.mainStage.initModality(Modality.WINDOW_MODAL);
        //Login.mainStage.initOwner(Login.mainStage);
        Scene scene = new Scene(root,600, 500);
        Stage secondStage = new Stage();
        secondStage.initModality(Modality.APPLICATION_MODAL);
        secondStage.initOwner(Login.mainStage);

        secondStage.setScene(scene);
        secondStage.show();
        //Login.mainStage.setScene(scene);


        // show the dialog and wait until the user closes it
        //Login.mainStage.showAndWait();


    }

    @FXML
    public void handleLogin(){
        tips.setText("");
        if(username.getText().trim().equals("")) {
            tips.setText(Tips.LOGIN_NO_USERNAME.getDesc());
            return;
        }
        if(password.getText().trim().equals("")) {
            tips.setText(Tips.LOGIN_NO_PASSWORD.getDesc());
            return;
        }

        String encodeUsername = null;
        String encodePassword = null;
        try {
            encodeUsername = EncryptUtils.SINGLETON.encryptByAes(username.getText());
            encodePassword = EncryptUtils.SINGLETON.encryptByAes(password.getText());
        } catch (Exception e) {
            e.printStackTrace();
            tips.setText(Tips.LOGIN_CLIENT_ERROR.getDesc());
        }

        JSONObject paramMap = new JSONObject();
        paramMap.put(LoginReqEnum.MOBILE.getKey(), encodeUsername);
        paramMap.put(LoginReqEnum.PASSWORD.getKey(), encodePassword);
        paramMap.put(LoginReqEnum.VERSION.getKey(), version);

        Map<String, Object> resMap = new HashMap<>();
        try {
            HttpPost post = new HttpPost("http://localhost:8081/crawler-api/api/login");
            HttpEntity entity = new StringEntity(paramMap.toString(),"UTF-8");
            post.setEntity(entity);
            post.setHeader(LoginReqEnum.CONTENT_TYPE.getKey(),LoginReqEnum.APPLICATION_JSON.getKey());

            CloseableHttpClient httpClient = HttpClients.custom().disableAutomaticRetries().build();
            HttpResponse response= httpClient.execute(post);

            JSONObject obj = JSON.parseObject(EntityUtils.toString(response.getEntity()));

            if(obj.getInteger(LoginResEnum.CODE.getKey()) == ServerCodeEnum.SUCCESS.getCode()) {
                JSONObject map = obj.getJSONObject(LoginResEnum.DATA.getKey());
                map.keySet().forEach(x -> {
                    try {
                        resMap.put(EncryptUtils.SINGLETON.decryptByAes(x), EncryptUtils.SINGLETON.decryptByAes(map.getString(x)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });

                String encodePaid = map.getString(LoginResEnum.PAID.getKey());
                String paidStr = encodePaid == null ? LoginResEnum.EMPTY.getKey() : EncryptUtils.SINGLETON.decryptByAes(encodePaid);
                if (Constants.PAID.equals(paidStr)) {
                    paid = true;
                }
                uid = map.getString(LoginResEnum.UID.getKey());
                showMainScene(resMap);
            } else {
                tips.setText(obj.getString(LoginResEnum.MSG.getKey()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            tips.setText(Tips.LOGIN_SERVER_ERROR.getDesc());
        }

    }
}
